/**
 *
 */
package steven.gui.console;

import java.io.Serializable;

/**
 * @author steven.lam.t.f
 *
 */
public class ConsoleLine implements Serializable{
	private static final long serialVersionUID = 5314348154066056703L;
	protected char[] chars;
	protected int length;
	protected int lineWidth;

	public ConsoleLine(){
		this.chars = new char[64];
		this.length = 0;
		this.lineWidth = 0;
	}
	public ConsoleLine(final String s){
		this.chars = s.toCharArray();
		this.length = this.chars.length;
		this.lineWidth = 0;
		for(int i = 0; i < this.length; i++){
			this.lineWidth += this.getWidth(this.chars[i]);
		}
	}
	public void append(final String s){
		final char[] content = s.toCharArray();
		this.ensureCapacity(content.length);
		System.arraycopy(content, 0, this.chars, this.length, content.length);
		this.length += content.length;
		for(final char c : content){
			this.lineWidth += this.getWidth(c);
		}
	}
	protected void ensureCapacity(final int additionalLength){
		final int expandLength = Math.max(this.chars.length, additionalLength);
		if(this.length + additionalLength > this.chars.length){
			final char[] newChars = new char[this.chars.length + expandLength];
			System.arraycopy(this.chars, 0, newChars, 0, this.length);
			this.chars = newChars;
		}
	}
	protected int getWidth(final char c){
		if(c < 256){
			return 1;
		}else{
			return 2;
		}
	}
	protected void clear(){
		this.length = 0;
		this.lineWidth = 0;
	}
}
